package com.mai4j.maiadmin.service.impl;

import com.mai4j.maiadmin.service.SettingService;
import com.mai4j.maiadmin.support.i18n.DefaultLocale;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Service
public class DefaultLocaleImpl implements DefaultLocale {
    /**
     * 配置服务
     */
    private final SettingService settingService;

    public DefaultLocaleImpl(SettingService settingService) {
        this.settingService = settingService;
    }

    @Override
    public Locale get(HttpServletRequest request) {
        String languageTag = String.valueOf(settingService.get("config").get("language.admin"));
        return Arrays.stream(Locale.getAvailableLocales())
                .filter(l -> Objects.equals(l.toLanguageTag(), languageTag))
                .findFirst()
                .orElse(Optional.ofNullable(request.getLocale()).orElse(Locale.SIMPLIFIED_CHINESE));
    }
}
